# -*- coding: utf-8 -*

import os
import sys
from random import randint

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import mplfinance as mpf

from aistock.settings import ROOT_H5_30MIN
from quantway.common.settings import ROOT_H5_DAY
import logging
from datetime import datetime





if __name__ == '__main__':
    ''' 
        usage python3 candlestick.py --single --level day --code sh000001 --startdate 20190101 --enddate 20190304
        --single 保留参数
        --level day， 30min
        --code  股票代码
        --startdate  开始日期
        --enddate 结束日期，不写的话，就是到文件最后一天
    '''
    # LOG_FORMAT = "%(message)s"
    # logging.basicConfig(filename=('log/candlestick-' + datetime.now().strftime("%Y%m%d" + ".log")),
    #                     level=logging.INFO, format=LOG_FORMAT)



    if "--single" in sys.argv:

        # 日k还是30分钟走势？
        level = sys.argv[sys.argv.index("--level")+1]
        # 该股代码
        code = sys.argv[sys.argv.index("--code")+1]
        startdate = sys.argv[sys.argv.index("--startdate")+1]
        if "--enddate" in sys.argv:
            enddate = sys.argv[sys.argv.index("--enddate")+1]
        else:
            enddate = None
        
        if level == "day":
            dataroot  = ROOT_H5_DAY    
        elif level == "30min":
            dataroot  = ROOT_H5_30MIN

        # 获取数据
        filepath = os.path.join(dataroot, code + '.h5')
        store = pd.HDFStore( filepath, 'r') 
        if enddate is None:
            df = store.select('data', where=['index>%s' % startdate], columns=['open','close','high','low','volume'])
        else:    
            df = store.select('data', where=['index>%s and index<%s' % \
                        (startdate, enddate)], columns=['open','close','high','low','volume'])
        store.close()
        df.open = df.open/1000.0
        df.close = df.close/1000.0
        df.high = df.high/1000.0
        df.low = df.low/1000.0
        
        df['dt'] = np.arange(0,len(df))
        df = df[['dt','open','close','high','low','volume']]
        
        print(df)

       
        mc = mpf.make_marketcolors(up='#ff1717',down='#53c156')
        s = mpf.make_mpf_style(marketcolors=mc)
        if level == "day":
            mpf.plot(df, type="candle", mav=((5,10,20,30)), volume=True, figratio=(1200/72,480/60), style=s, datetime_format='%Y-%m-%d',xrotation=45)
        else:
            mpf.plot(df, type="candle",  figratio=(1200/72,480/60), style=s, datetime_format='%Y-%m-%d %H:%M',xrotation=45)
                












